/**
 *  Copyright 2002 Quaseem
 *  Copyright 2004 Migisan
 *  Copyright 2008 Oest
 *
 *  This file is part of the aochat package.
 *
 *  The aochat package is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The aochat package is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with the aochat package; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

package sk.sigp.aobot.client.core;

import java.util.Vector;

import sk.sigp.aobot.client.BotCore;
import sk.sigp.aobot.client.core.message.general.Message;

public class MessageQueue implements Runnable {
	protected BotCore boss;
	protected Thread myThread;
	@SuppressWarnings("unchecked")
	protected Vector queue = new Vector();
	protected Message last = null;

	public static int MIN_DELAY = 1000;
	public static int MAX_DELAY = 10000;

	protected int delayTime = MIN_DELAY + MAX_DELAY / 2;

	public MessageQueue(BotCore master) {
		boss = master;
	}

	public synchronized void add(Message[] msgs, boolean priority) {
		for (int i = 0; i < msgs.length; i++)
			add(msgs[i], priority);
	}

	@SuppressWarnings("unchecked")
	public synchronized void add(Message msg, boolean priority) {
		if (priority == false) {
			queue.addElement(msg);
			System.out.println("Added msg to queue. Queue size is " + size());
		} else {
			System.out.println("Added PRIORITY msg to queue. Queue size is " + size());
			queue.insertElementAt(msg, 0);
		}
		if (myThread == null) {
			myThread = new Thread(this);
			myThread.start();
		}
	}

	public void resend() {
		if (last != null) {
			add(last, true);
			last = null;
			delayTime += 250;
		}
	}

	public int getDelayTime() {
		return delayTime;
	}

	public boolean isEmpty() {
		return queue.isEmpty();
	}

	public int size() {
		return queue.size();
	}

	public void run() {
		int sleep = MIN_DELAY;
		while (queue.size() > 0) {
			dispatchMessage();

			if (sleep < delayTime)
				sleep += 1000;
			if (sleep > delayTime)
				sleep = delayTime;

			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
			}
			if (delayTime > MIN_DELAY)
				delayTime -= 10;
		}
	}

	private synchronized void dispatchMessage() {
		Message sendNow = (Message) queue.elementAt(0);
		queue.removeElementAt(0);

		last = sendNow;
		boss.send(sendNow);
		if (queue.size() == 0) {
			System.out.println("Queue is empty.");
			myThread = null;
		}
	}
}
